//////////////////////////////////////////////////////////////////////////
//	Name: CDXRenderWin32.cpp
//	Purpose: Creates and displays a "Render to Texture quad!"
//	Created: November 15, 2009
//////////////////////////////////////////////////////////////////////////

#include "CDXRenderToTexture.h"



bool CDXRenderToTexture::InitR2T()
{
	D3DVERTEX aQuad[] = {{1.0f,-1.0f,10.0f,0xffffff00},
	{3.0f,-1.0f,10.0f,0xffffff00},
	{1.0f, 1.0f,10.0f,0xffffff00},
	{3.0f, 1.0f,10.0f,0xffffff00}};


	m_pDXRW32 = CDXRenderWin32::GetInstance();
	m_pDXRW32->GetDevice()->CreateTexture(256,256,1,D3DUSAGE_RENDERTARGET,D3DFMT_R5G6B5,D3DPOOL_DEFAULT,&m_pRenderTexture,NULL);
	//m_pDXRW32->GetDevice()->CreateTexture(GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN),1,D3DUSAGE_RENDERTARGET,D3DFMT_R5G6B5,D3DPOOL_DEFAULT,&m_pRenderTexture,NULL);
	m_pRenderTexture->GetSurfaceLevel(0,&m_pRenderSurface);


	//create a projection matrix that fits to the texture dimensions, 
	//because the aspect ratio of the texture is not the same as the back buffers one
	D3DXMatrixPerspectiveFovLH(&m_matProjection,D3DX_PI / 4.0f,1,1,100);

	//Save the old Proj mat.
	m_pDXRW32->GetDevice()->GetTransform(D3DTS_PROJECTION,&m_matOldProjection);
	m_pDXRW32->GetDevice()->GetRenderTarget(0,&m_pBackBuffer);


	m_pDXRW32->GetDevice()->CreateVertexBuffer(sizeof(aQuad),
		D3DUSAGE_WRITEONLY,
		D3DFVF_CUSTOMVERTEX,
		D3DPOOL_MANAGED,
		&pQuadVB,
		NULL);

	return true;
}

bool CDXRenderToTexture::ShutDownR2T()
{

	m_pRenderSurface->Release();
	m_pRenderSurface = NULL;

	m_pBackBuffer->Release();
	m_pBackBuffer = NULL;
	return true;

}

void CDXRenderToTexture::StartR2T()
{
	m_pDXRW32->GetDevice()->SetRenderTarget(0,m_pRenderSurface);
}

void CDXRenderToTexture::RenderPassR2T(D3DMATRIX matTranslation)
{
	m_pDXRW32->GetDevice()->SetRenderTarget(0,m_pBackBuffer);
	m_pDXRW32->GetDevice()->Clear(0,
		NULL,
		D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
		D3DCOLOR_XRGB(0,0,0),
		1.0f,
		0);
	m_pDXRW32->GetDevice()->BeginScene();

	//set rendered texture
	m_pDXRW32->GetDevice()->SetTexture(0,m_pRenderTexture);

	//m_pDXRW32->GetDevice()->SetTransform(D3DTS_WORLD,&matTranslation);
	//restore projection matrix
	m_pDXRW32->GetDevice()->SetTransform(D3DTS_PROJECTION,&m_matOldProjection);

	m_pDXRW32->GetDevice()->SetStreamSource(0,pQuadVB,0,sizeof(D3DVERTEX));
	m_pDXRW32->GetDevice()->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2);

	m_pDXRW32->GetDevice()->EndScene();

	m_pDXRW32->GetDevice()->Present(NULL,NULL,NULL,NULL);
}